"""
会员系统模块
基于积分系统提供会员等级管理、特权设置、升级规则等功能
"""

import json
from pathlib import Path
from typing import Dict, Any, List, Optional
from datetime import datetime, timedelta
import uuid

# 会员数据存储路径
MEMBERSHIP_DATA_PATH = Path(__file__).parent.parent / "data" / "membership.json"

# 会员等级定义
MEMBERSHIP_LEVELS = {
    "bronze": {
        "name": "青铜会员",
        "icon": "🥉",
        "min_points": 0,
        "min_orders": 0,
        "min_spending": 0,
        "benefits": {
            "discount_rate": 0.02,  # 2%折扣
            "free_shipping_threshold": 99,  # 满99元免运费
            "points_multiplier": 1.0,  # 积分倍率
            "priority_support": False,
            "birthday_bonus": 10,
            "monthly_coupons": 1
        }
    },
    "silver": {
        "name": "白银会员",
        "icon": "🥈",
        "min_points": 500,
        "min_orders": 5,
        "min_spending": 1000,
        "benefits": {
            "discount_rate": 0.05,  # 5%折扣
            "free_shipping_threshold": 59,  # 满59元免运费
            "points_multiplier": 1.2,  # 1.2倍积分
            "priority_support": False,
            "birthday_bonus": 25,
            "monthly_coupons": 2
        }
    },
    "gold": {
        "name": "黄金会员",
        "icon": "🥇",
        "min_points": 1500,
        "min_orders": 15,
        "min_spending": 3000,
        "benefits": {
            "discount_rate": 0.08,  # 8%折扣
            "free_shipping_threshold": 0,  # 免费配送
            "points_multiplier": 1.5,  # 1.5倍积分
            "priority_support": True,
            "birthday_bonus": 50,
            "monthly_coupons": 3
        }
    },
    "platinum": {
        "name": "铂金会员",
        "icon": "💎",
        "min_points": 3000,
        "min_orders": 30,
        "min_spending": 8000,
        "benefits": {
            "discount_rate": 0.12,  # 12%折扣
            "free_shipping_threshold": 0,  # 免费配送
            "points_multiplier": 2.0,  # 2倍积分
            "priority_support": True,
            "birthday_bonus": 100,
            "monthly_coupons": 5,
            "exclusive_products": True,  # 专属商品
            "personal_advisor": True  # 专属顾问
        }
    },
    "diamond": {
        "name": "钻石会员",
        "icon": "💍",
        "min_points": 6000,
        "min_orders": 60,
        "min_spending": 20000,
        "benefits": {
            "discount_rate": 0.15,  # 15%折扣
            "free_shipping_threshold": 0,  # 免费配送
            "points_multiplier": 3.0,  # 3倍积分
            "priority_support": True,
            "birthday_bonus": 200,
            "monthly_coupons": 8,
            "exclusive_products": True,
            "personal_advisor": True,
            "vip_hotline": True,  # VIP热线
            "annual_gift": True  # 年度礼品
        }
    }
}

def _initialize_membership_data():
    """初始化会员数据文件"""
    if not MEMBERSHIP_DATA_PATH.exists():
        # 创建数据目录
        MEMBERSHIP_DATA_PATH.parent.mkdir(parents=True, exist_ok=True)
        
        default_data = {
            "memberships": {},
            "membership_history": [],
            "monthly_coupons_issued": {},
            "created_at": datetime.now().isoformat()
        }
        with open(MEMBERSHIP_DATA_PATH, 'w', encoding='utf-8') as f:
            json.dump(default_data, f, ensure_ascii=False, indent=2)
        return default_data
    
    try:
        with open(MEMBERSHIP_DATA_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"读取会员数据文件失败: {e}")
        return {
            "memberships": {},
            "membership_history": [],
            "monthly_coupons_issued": {},
            "created_at": datetime.now().isoformat()
        }

def _save_membership_data(data: Dict[str, Any]) -> bool:
    """保存会员数据"""
    try:
        # 确保目录存在
        MEMBERSHIP_DATA_PATH.parent.mkdir(parents=True, exist_ok=True)
        
        with open(MEMBERSHIP_DATA_PATH, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存会员数据失败: {e}")
        return False

def get_user_membership(user_id: str) -> Dict[str, Any]:
    """获取用户会员信息"""
    data = _initialize_membership_data()
    user_membership = data["memberships"].get(user_id, {
        "level": "bronze",
        "joined_date": datetime.now().isoformat(),
        "points_earned": 0,
        "total_orders": 0,
        "total_spending": 0,
        "last_upgrade": datetime.now().isoformat(),
        "monthly_coupons_used": 0,
        "benefits_used": {},
        "vip_expires": None
    })
    
    # 添加等级信息
    level_info = MEMBERSHIP_LEVELS.get(user_membership["level"], MEMBERSHIP_LEVELS["bronze"])
    user_membership.update({
        "level_name": level_info["name"],
        "level_icon": level_info["icon"],
        "benefits": level_info["benefits"]
    })
    
    return user_membership

def calculate_membership_level(points: int, orders: int, spending: float) -> str:
    """根据积分、订单数和消费金额计算会员等级"""
    # 从最高等级开始检查
    for level_id in reversed(list(MEMBERSHIP_LEVELS.keys())):
        level = MEMBERSHIP_LEVELS[level_id]
        if (points >= level["min_points"] and 
            orders >= level["min_orders"] and 
            spending >= level["min_spending"]):
            return level_id
    
    return "bronze"  # 默认青铜会员

def update_user_membership(user_id: str, points: int = None, orders: int = None, spending: float = None) -> Dict[str, Any]:
    """更新用户会员信息"""
    data = _initialize_membership_data()
    
    # 获取当前会员信息
    current_membership = data["memberships"].get(user_id, {
        "level": "bronze",
        "joined_date": datetime.now().isoformat(),
        "points_earned": 0,
        "total_orders": 0,
        "total_spending": 0,
        "last_upgrade": datetime.now().isoformat(),
        "monthly_coupons_used": 0,
        "benefits_used": {},
        "vip_expires": None
    })
    
    # 更新统计数据
    if points is not None:
        current_membership["points_earned"] = points
    if orders is not None:
        current_membership["total_orders"] = orders
    if spending is not None:
        current_membership["total_spending"] = spending
    
    # 计算新等级
    old_level = current_membership["level"]
    new_level = calculate_membership_level(
        current_membership["points_earned"],
        current_membership["total_orders"],
        current_membership["total_spending"]
    )
    
    # 检查是否升级
    upgrade_info = None
    if new_level != old_level:
        # 检查新等级是否比旧等级高
        level_order = list(MEMBERSHIP_LEVELS.keys())
        if level_order.index(new_level) > level_order.index(old_level):
            current_membership["level"] = new_level
            current_membership["last_upgrade"] = datetime.now().isoformat()
            
            # 记录升级历史
            upgrade_record = {
                "user_id": user_id,
                "old_level": old_level,
                "new_level": new_level,
                "upgrade_date": datetime.now().isoformat(),
                "points_at_upgrade": current_membership["points_earned"],
                "orders_at_upgrade": current_membership["total_orders"],
                "spending_at_upgrade": current_membership["total_spending"]
            }
            
            data["membership_history"].append(upgrade_record)
            
            upgrade_info = {
                "upgraded": True,
                "old_level": MEMBERSHIP_LEVELS[old_level]["name"],
                "new_level": MEMBERSHIP_LEVELS[new_level]["name"],
                "new_benefits": MEMBERSHIP_LEVELS[new_level]["benefits"]
            }
    
    # 保存数据
    data["memberships"][user_id] = current_membership
    _save_membership_data(data)
    
    # 返回结果
    result = get_user_membership(user_id)
    if upgrade_info:
        result["upgrade_info"] = upgrade_info
    
    return result

def check_discount_eligibility(user_id: str, order_amount: float) -> Dict[str, Any]:
    """检查用户是否享受会员折扣"""
    membership = get_user_membership(user_id)
    benefits = membership["benefits"]
    
    discount_rate = benefits.get("discount_rate", 0)
    discount_amount = order_amount * discount_rate
    final_amount = order_amount - discount_amount
    
    return {
        "eligible": discount_rate > 0,
        "discount_rate": discount_rate,
        "discount_amount": discount_amount,
        "original_amount": order_amount,
        "final_amount": final_amount,
        "level": membership["level"],
        "level_name": membership["level_name"]
    }

def check_free_shipping_eligibility(user_id: str, order_amount: float) -> Dict[str, Any]:
    """检查用户是否享受免运费"""
    membership = get_user_membership(user_id)
    benefits = membership["benefits"]
    
    threshold = benefits.get("free_shipping_threshold", 99)
    eligible = order_amount >= threshold
    
    return {
        "eligible": eligible,
        "threshold": threshold,
        "order_amount": order_amount,
        "level": membership["level"],
        "level_name": membership["level_name"]
    }

def grant_vip_membership(user_id: str, duration_days: int = 30) -> Dict[str, Any]:
    """授予临时VIP会员资格（通过积分兑换）"""
    data = _initialize_membership_data()
    
    # 获取当前会员信息
    current_membership = data["memberships"].get(user_id, {
        "level": "bronze",
        "joined_date": datetime.now().isoformat(),
        "points_earned": 0,
        "total_orders": 0,
        "total_spending": 0,
        "last_upgrade": datetime.now().isoformat(),
        "monthly_coupons_used": 0,
        "benefits_used": {},
        "vip_expires": None
    })
    
    # 设置VIP过期时间
    vip_expires = datetime.now() + timedelta(days=duration_days)
    current_membership["vip_expires"] = vip_expires.isoformat()
    
    # 如果当前等级低于黄金，临时提升到黄金
    if current_membership["level"] in ["bronze", "silver"]:
        current_membership["temp_level"] = "gold"
    
    # 保存数据
    data["memberships"][user_id] = current_membership
    _save_membership_data(data)
    
    return {
        "success": True,
        "message": f"VIP会员已激活，有效期{duration_days}天",
        "expires_at": vip_expires.isoformat(),
        "temp_benefits": MEMBERSHIP_LEVELS["gold"]["benefits"]
    }

def check_vip_status(user_id: str) -> bool:
    """检查VIP状态是否有效"""
    membership = get_user_membership(user_id)
    vip_expires = membership.get("vip_expires")
    
    if not vip_expires:
        return False
    
    try:
        expires_date = datetime.fromisoformat(vip_expires)
        return datetime.now() < expires_date
    except:
        return False

def get_next_level_requirements(user_id: str) -> Dict[str, Any]:
    """获取升级到下一等级的要求"""
    membership = get_user_membership(user_id)
    current_level = membership["level"]
    
    # 获取等级顺序
    level_order = list(MEMBERSHIP_LEVELS.keys())
    current_index = level_order.index(current_level)
    
    if current_index >= len(level_order) - 1:
        return {
            "is_max_level": True,
            "message": "您已达到最高会员等级！"
        }
    
    next_level = level_order[current_index + 1]
    next_level_info = MEMBERSHIP_LEVELS[next_level]
    
    current_points = membership.get("points_earned", 0)
    current_orders = membership.get("total_orders", 0)
    current_spending = membership.get("total_spending", 0)
    
    points_needed = max(0, next_level_info["min_points"] - current_points)
    orders_needed = max(0, next_level_info["min_orders"] - current_orders)
    spending_needed = max(0, next_level_info["min_spending"] - current_spending)
    
    return {
        "is_max_level": False,
        "next_level": next_level,
        "next_level_name": next_level_info["name"],
        "next_level_icon": next_level_info["icon"],
        "requirements": {
            "points_needed": points_needed,
            "orders_needed": orders_needed,
            "spending_needed": spending_needed
        },
        "current_progress": {
            "points": current_points,
            "orders": current_orders,
            "spending": current_spending
        },
        "next_level_targets": {
            "points": next_level_info["min_points"],
            "orders": next_level_info["min_orders"],
            "spending": next_level_info["min_spending"]
        },
        "next_benefits": next_level_info["benefits"]
    }

def get_membership_statistics() -> Dict[str, Any]:
    """获取会员系统统计信息"""
    data = _initialize_membership_data()
    memberships = data.get("memberships", {})
    
    # 统计各等级人数
    level_counts = {}
    total_members = len(memberships)
    
    for level_id in MEMBERSHIP_LEVELS.keys():
        level_counts[level_id] = 0
    
    for membership in memberships.values():
        level = membership.get("level", "bronze")
        level_counts[level] = level_counts.get(level, 0) + 1
    
    # 计算升级次数
    upgrade_history = data.get("membership_history", [])
    total_upgrades = len(upgrade_history)
    
    return {
        "total_members": total_members,
        "level_distribution": level_counts,
        "total_upgrades": total_upgrades,
        "upgrade_history": upgrade_history[-10:],  # 最近10次升级
        "level_percentages": {
            level: (count / total_members * 100) if total_members > 0 else 0
            for level, count in level_counts.items()
        }
    }
